package com.travelplanning.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.travelplanning.admin.common.biz.user.UserContext;
import com.travelplanning.admin.common.enums.UserErrorCodeEnum;
import com.travelplanning.admin.common.exception.ClientException;
import com.travelplanning.admin.common.exception.ServiceException;
import com.travelplanning.admin.dao.entity.UserDO;
import com.travelplanning.admin.dao.mapper.UserMapeper;
import com.travelplanning.admin.dto.req.UserLoginReqDTO;
import com.travelplanning.admin.dto.req.UserRegisterReqDTO;
import com.travelplanning.admin.dto.req.UserUpdateReqDTO;
import com.travelplanning.admin.dto.resp.UserLoginRespDTO;
import com.travelplanning.admin.dto.resp.UserRespDTO;
import com.travelplanning.admin.service.UserService;
import com.travelplanning.admin.util.JWTUtils;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.travelplanning.admin.common.constant.RedisCacheConstant.LOCK_USER_LOGIN_KEY;
import static com.travelplanning.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.travelplanning.admin.common.enums.UserErrorCodeEnum.USER_NAME_EXIST;


/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapeper, UserDO> implements UserService {
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public UserRespDTO getUserByUsername() {
        String username = UserContext.getUsername();
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ServiceException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
        Boolean he=userRegisterCachePenetrationBloomFilter.contains(username);
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestparam) {
        if (!hasUsername(requestparam.getUsername())){
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY+requestparam.getUsername());
        try{
            if (lock.tryLock()){
                int insert = baseMapper.insert(BeanUtil.toBean(requestparam, UserDO.class));
                if (insert<1){
                    throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
                }
                userRegisterCachePenetrationBloomFilter.add(requestparam.getUsername());
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO requestparam) {
        String userId = UserContext.getUserId();
        if (requestparam.getOldpassword()!=null){
            LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                    .eq(UserDO::getId, userId)
                    .eq(UserDO::getPassword, requestparam.getOldpassword());
            UserDO userDO = baseMapper.selectOne(updateWrapper);
            if (userDO==null){
                throw new ClientException("旧密码错误");
            }
            LambdaUpdateWrapper<UserDO> updateWrapper1 = Wrappers.lambdaUpdate(UserDO.class)
                    .eq(UserDO::getId, userId);
            baseMapper.update(BeanUtil.toBean(requestparam,UserDO.class),updateWrapper1);
        }

        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getId, userId);
        baseMapper.update(BeanUtil.toBean(requestparam,UserDO.class),updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestparam) {
        RLock lock = redissonClient.getLock(LOCK_USER_LOGIN_KEY+requestparam.getUsername());
        try{
            if (lock.tryLock()){
                LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                        .eq(UserDO::getUsername, requestparam.getUsername())
                        .eq(UserDO::getPassword, requestparam.getPassword())
                        .eq(UserDO::getDelFlag, 0);
                UserDO userDO = baseMapper.selectOne(queryWrapper);
                if (userDO==null){
                    throw new ClientException("用户不存在或密码错误");
                }
                Boolean hasLogin = stringRedisTemplate.hasKey("login_" + requestparam.getUsername());
//                if (hasLogin!=null && hasLogin) {
//                    throw new ClientException("用户已登录");
//                }
                Map<String,String> payload = new HashMap<>();

                payload.put("userid",userDO.getId().toString());
                payload.put("username",userDO.getUsername());
                //生成JWT令牌
                String token = JWTUtils.getToken(payload);
                stringRedisTemplate.opsForHash().put("login_"+requestparam.getUsername(),token,JSON.toJSONString(userDO));
                stringRedisTemplate.expire("login_"+requestparam.getUsername(),30L, TimeUnit.DAYS);

                return new UserLoginRespDTO(token);
            }
            throw new ClientException(USER_NAME_EXIST);
        }finally {
            lock.unlock();
        }

    }

    @Override
    public Boolean checkLogin(String username,String token) {

        return stringRedisTemplate.opsForHash().get("login_"+username,token)!=null;

    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username,token)){
            stringRedisTemplate.opsForHash().delete("login_"+username);
            return;
        }
        throw new ClientException("用户token不存在或用户未登录");
    }

}
